<?php

namespace Summer\Shop\Http\Controllers;

use Carbon\Carbon;
use Illuminate\Routing\Controller;
use RLuders\JWTAuth\Classes\JWTAuth;
use Input;
use Config;
use Exception;
use Db;
use Summer\Hjd\Classes\CommonApi;
use Summer\Hjd\Models\WalletModel;
use Summer\Hub\Http\Controllers\Traits\ApiReturn;
use Summer\Location\Models\UserAddressModel;
use Summer\Shop\Models\CartModel;
use Summer\Shop\Models\OrderItemModel;
use Summer\Shop\Models\OrderModel;
use ApplicationException;
use Summer\Shop\Models\ProductModel;
use Summer\Shop\Models\RegGoodsModel;
use Summer\Shop\Models\ScoreGoodsModel;

class OrderController extends Controller
{
    use ApiReturn;

    /**
     * 确认收货
     * @param JWTAuth $auth
     * @return \Illuminate\Http\JsonResponse
     */
    public function confirm(JWTAuth $auth){
        if (!$user = $auth->user()) {
            return $this->apiError('登录失效,请重新登录');
        }
        if(!Input::has('id')){
            return $this->apiError('参数错误');
        }
        $order_id=Input::get('id');
        $order=OrderModel::where('id',$order_id)->where('user_id',$user->id)->where('status',1)->where('status_slug','noget')->first();
        if(!$order){
            return $this->apiError('订单已失效');
        }
        $order->status_slug='nocomment';
        $order->complete_at=Carbon::now();
        $order->save();
        //订单商品状态修改
        OrderItemModel::where('order_id',$order->id)->update(['status_slug'=>'nocomment']);
        return $this->apiSuccess('操作成功');
    }
    /**
     * 删除订单
     * @param JWTAuth $auth
     * @return \Illuminate\Http\JsonResponse
     */
    public function delete(JWTAuth $auth){
        if (!$user = $auth->user()) {
            return $this->apiError('登录失效,请重新登录');
        }
        if(!Input::has('id')){
            return $this->apiError('参数错误');
        }
        $order_id=Input::get('id');
        OrderModel::where('id',$order_id)->where('user_id',$user->id)->whereIn('status',[-1,-2,2])->delete();
        OrderItemModel::where('order_id',$order_id)->delete();
        return $this->apiSuccess('操作成功');
    }
    /**
     * 取消订单
     * @param JWTAuth $auth
     * @return \Illuminate\Http\JsonResponse
     */
    public function cancel(JWTAuth $auth){
        if (!$user = $auth->user()) {
            return $this->apiError('登录失效,请重新登录');
        }
        if(!Input::has('id')){
            return $this->apiError('参数错误');
        }
        $order_id=Input::get('id');
        $order=OrderModel::where('id',$order_id)->where('user_id',$user->id)->where('status',0)->where('status_slug','nopay')->first();
        if(!$order){
            return $this->apiError('该订单不支持次操作');
        }
        $order->status=-1;
        $order->status_slug='cancel';
        $order->save();
        //订单商品状态修改
        OrderItemModel::where('order_id',$order->id)->update(['status_slug'=>'cancel']);
        return $this->apiSuccess('操作成功');

    }

    /**
     * 支付订单
     * @param JWTAuth $auth
     * @return \Illuminate\Http\JsonResponse
     */
    public function pay(JWTAuth $auth){
        if (!$user = $auth->user()) {
            return $this->apiError('登录失效,请重新登录');
        }
        $order_sn=Input::get('order_sn');
        if(!$order_sn){
            return $this->apiError('参数错误');
        }
        $order=OrderModel::where('order_sn',$order_sn)->where('user_id',$user->id)->where('status',0)->where('status_slug','nopay')->where('is_pay',0)->first();
        if(!$order){
            return $this->apiError('订单已失效');
        }
        //支付信息
        $payment=Input::get('payment');
        if($payment=='wallet'){//平台货币支付

            $currency_slug=Input::get('currency_slug');
            if(!$currency_slug){
                return $this->apiError('请选择支付币种');
            }
//            $currency_slug='bonus';//奖金钱包。根据需求修改或配置
            $money=$order->total;
            //余额判断
            $balancr=WalletModel::where('currency_slug',$currency_slug)->where('user_id',$user->id)->value('balance');
            if($money>$balancr){
                return $this->apiError('余额不足');
            }
            //购物扣除
            $commonapi=new CommonApi();
            $commonapi->settleDetailed($user->id,$user->id,$money,0,$currency_slug,[
                'change_slug'=>'order_pay',
                'table_id'=>$order->id,
                'table_name'=>'summer_shop_orders'

            ]);
            $order->is_pay=1;
            $order->pay_at=Carbon::now();
            $order->status=1;
            $order->status_slug='nosend';
            //订单商品状态修改
            OrderItemModel::where('order_id',$order->id)->update(['status_slug'=>'nosend']);
        }
        $order->save();
        return $this->apiSuccess('操作成功',$order);
    }

    /**
     * 订单详情
     * @param JWTAuth $auth
     * @return \Illuminate\Http\JsonResponse
     */
    public function preview(JWTAuth $auth){
        if (!$user = $auth->user()) {
            return $this->apiError('登录失效,请重新登录');
        }
        $order_id=Input::get('id');
        if(!$order_id){
            return $this->apiError('参数错误');
        }
        $order=OrderModel::where('id',$order_id)->where('user_id',$user->id)->first();
        $order_item_status_slug_config=Config::get('summer.shop::order_item_status_slug');
        $order->items->each(function ($item) use($order_item_status_slug_config){
            $item->thumb_path=url('/storage/app/'.$item->thumb);
            $item->btns=$order_item_status_slug_config[$item->status_slug]['btns'];
            $item->status_name=$order_item_status_slug_config[$item->status_slug]['title'];
        });
        $order_status_slug_config=Config::get('summer.shop::order_status_slug');
        $order->status_code=$order->status_slug;
        $order->status_desc=$order_status_slug_config[$order->status_slug]['comment'];
        $order->status_name=$order_status_slug_config[$order->status_slug]['title'];
        $order->btns=$order_status_slug_config[$order->status_slug]['btns'];

        $order->score_fee=$order->score_amount;

        return $this->apiSuccess('操作成功',$order);
    }

    /**
     * 物流信息
     * @param JWTAuth $auth
     * @return \Illuminate\Http\JsonResponse
     */
    public function express(JWTAuth $auth){
        if (!$user = $auth->user()) {
            return $this->apiError('登录失效,请重新登录');
        }
        $order_id=Input::get('order_id');
        if(!$order_id){
            return $this->apiError('参数错误');
        }
        $order=OrderModel::where('id',$order_id)->where('user_id',$user->id)->first();
        $order->items->each(function ($item){
            $item->thumb_path=url('/storage/app/'.$item->thumb);
        });
        $order_status_slug_config=Config::get('summer.shop::order_status_slug');
        $order->status_code=$order->status_slug;
        $order->status_desc=$order_status_slug_config[$order->status_slug]['comment'];
        $order->status_name=$order_status_slug_config[$order->status_slug]['title'];
        $order->btns=$order_status_slug_config[$order->status_slug]['btns'];
        $order->log=[];
        return $this->apiSuccess('操作成功',$order);
    }

    /**
     * 订单商品详情
     * @param JWTAuth $auth
     */
    public function itemDetail(JWTAuth $auth){
        if (!$user = $auth->user()) {
            return $this->apiError('登录失效,请重新登录');
        }
        $order_id=Input::get('id');
        if(!$order_id){
            return $this->apiError('参数错误');
        }
        $order_item_id=Input::get('order_item_id');
        if(!$order_item_id){
            return $this->apiError('参数错误');
        }
        $order_item=OrderItemModel::where('user_id',$user->id)->where('id',$order_item_id)->where('order_id',$order_id)->first();
        if(!$order_item){
            return $this->apiError('订单商品信息获取失败');
        }
        $order_item->thumb_path=url('/storage/app/'.$order_item->thumb);
        $order_item_status_slug_config=Config::get('summer.shop::order_item_status_slug');
        $order_item->btns=$order_item_status_slug_config[$order_item->status_slug]['btns'];
        $order_item->status_name=$order_item_status_slug_config[$order_item->status_slug]['title'];
        return $this->apiSuccess('操作成功',$order_item);
    }
    /**
     * 我的订单
     * @param JWTAuth $auth
     * @return \Illuminate\Http\JsonResponse
     */
    public function index(JWTAuth $auth){
        if (!$user = $auth->user()) {
            return $this->apiError('登录失效,请重新登录');
        }
        $page_size=Input::get('page_size')??20;
        $page=Input::get('page')??1;

        $query=OrderModel::select();
        $query->with(['items']);
        $query->where('user_id',$user->id);

        if(Input::has('type')){
            $type=Input::get('type');
            if($type!='all'){
                $query->where('status_slug',$type);
            }
        }
        $query->orderBy('id','DESC');
        $records=$query->paginate($page_size,$page);
        $order_status_slug_config=Config::get('summer.shop::order_status_slug');
        $order_item_status_slug_config=Config::get('summer.shop::order_item_status_slug');
        $records->each(function ($record)use($order_status_slug_config,$order_item_status_slug_config){
            $record->items->each(function ($item)use($order_item_status_slug_config){
                $item->thumb_path=url('/storage/app/'.$item->thumb);
                $item->btns=$order_item_status_slug_config[$item->status_slug]['btns'];
                $item->status_name=$order_item_status_slug_config[$item->status_slug]['title'];
            });
            $record->status_code=$record->status_slug;
            $record->status_desc=$order_status_slug_config[$record->status_slug]['comment'];
            $record->status_name=$order_status_slug_config[$record->status_slug]['title'];
            $record->btns=$order_status_slug_config[$record->status_slug]['btns'];
        });
        $return['records']=$records;
        return $this->apiSuccess('操作成功',$return);
    }
    /**
     * 提交订单
     * @param JWTAuth $auth
     */
    public function submit(JWTAuth $auth){
        if (!$user = $auth->user()) {
            return $this->apiError('登录失效,请重新登录');
        }
        $from=Input::get('from');
        $goods_list=Input::get('goods_list');
        $address_id=Input::get('address_id');
        $remark=Input::get('remark','');
        $order_type=Input::get('order_type');
        $params['order_type']=$order_type;//额外参数
        Db::beginTransaction();
        try {
            $useraddress=UserAddressModel::with([
                'province'=>function($q){$q->select('code','name');},
                'city'=>function($q){$q->select('code','name');},
                'area'=>function($q){$q->select('code','name');},
            ])->where('id',$address_id)->where('user_id',$user->id)->first();
            if(!$useraddress){
                throw new ApplicationException('地址参数错误');
            }
            $user_address_data['province_code']=$useraddress->province->code;
            $user_address_data['province_name']=$useraddress->province->name;
            $user_address_data['city_name']=$useraddress->city->name;
            $user_address_data['city_code']=$useraddress->city->code;
            $user_address_data['area_name']=$useraddress->area->name;
            $user_address_data['area_code']=$useraddress->area->code;
            $user_address_data['address']=$useraddress->address;
            $user_address_data['consignee']=$useraddress->consignee;
            $user_address_data['phone']=$useraddress->phone;
            $check_order=$this->check($goods_list,$user,$params);
            $order_sn=getSn($user->id);
            $order=new OrderModel();
            $order->order_sn=$order_sn;
            $order->user_id=$user->id;
            $order->user_address=$user_address_data;
            $order->coupon_fee=$check_order['coupon_fee'];
            $order->discount_fee=$check_order['discount_fee'];
            $order->goods_amount=$check_order['goods_amount'];
            $order->invoice_amount=$check_order['invoice_amount'];
            $order->dispatch_amount=$check_order['dispatch_amount'];
            $order->dispatch_discount_money=$check_order['dispatch_discount_money'];
            $order->total=$check_order['total'];
            $order->score_amount=$check_order['score_amount'];
            $order->pv=$check_order['pv']??0;
            $order->status=0;
            $order->status_slug='nopay';
            $order->remark=$remark;
            $order->save();
            foreach($check_order['items'] as $k=>$v){
                unset($check_order['items'][$k]['thumb_path']);
                $check_order['items'][$k]['user_id']=$user->id;
                $check_order['items'][$k]['order_id']=$order->id;
                $check_order['items'][$k]['created_at']=Carbon::now();
                $check_order['items'][$k]['updated_at']=Carbon::now();
                $check_order['items'][$k]['status_slug']='nopay';
                $check_order['items'][$k]['score_amount']=$v['score']??0;
                unset($check_order['items'][$k]['score']);
            }
            $items_table=new OrderItemModel();
            $items_table->insert($check_order['items']);
            //积分商城处理
            if($order_type=='score'){
                $currency_slug='score';//积分钱包。根据需求修改或配置
                $money=$order->score_amount;
                //余额判断
                $balancr=WalletModel::where('currency_slug',$currency_slug)->where('user_id',$user->id)->value('balance');
                if($money>$balancr){
                    throw new ApplicationException('余额不足');
                }
                //购物扣除
                $commonapi=new CommonApi();
                $commonapi->settleDetailed($user->id,$user->id,$money,0,$currency_slug,[
                    'change_slug'=>'order_pay',
                    'table_id'=>$order->id,
                    'table_name'=>'summer_shop_orders'

                ]);
                if($order->total==0){//如果只需积分兑换的话
                    $order->is_pay=1;
                    $order->pay_at=Carbon::now();
                    $order->status=1;
                    $order->status_slug='nosend';
                    //订单商品状态修改
                    OrderItemModel::where('order_id',$order->id)->update(['status_slug'=>'nosend']);
                    $order->save();
                }
            }

            //删除购物车
            if($from=='cart'){
                foreach($check_order['items'] as $v){
                    CartModel::where('user_id',$user->id)->where('product_id',$v['product_id'])->where('index',$v['index'])->delete();
                }
            }
            Db::commit();
            return $this->apiSuccess('操作成功',$order);
        }catch (Exception $e){
            Db::rollBack();
            return $this->apiError($e->getMessage());
        }
    }

    /**
     * 预订单
     * @param JWTAuth $auth
     * @return \Illuminate\Http\JsonResponse
     */
    public function checkCreate(JWTAuth $auth){
        if (!$user = $auth->user()) {
            return $this->apiError('登录失效,请重新登录');
        }
        $from=Input::get('from');
        $goods_list=Input::get('goods_list');
        $order_type=Input::get('order_type');
        $params['order_type']=$order_type;//额外参数
        try {
            $return=$this->check($goods_list,$user,$params);
            return $this->apiSuccess('操作成功',$return);
        }catch (Exception $e){
            return $this->apiError($e->getMessage());
        }
    }

    /**
     * 订单信息检测
     * @param $goods_list 商品列表
     * @param $user 用户信息,用来获取折扣信息
     */
    protected function check($goods_list,$user,$params){
        $total=0;
        $coupon_fee=0;//优惠金额
        $discount_fee=0;//打折金额
        $goods_amount=0;//商品总额
        $invoice_amount=0;//发票金额
        $dispatch_amount=0;//订单运费
        $dispatch_discount_money=0;//运费折扣金额
        $score_amount=0;//积分总额
        $order_pv=0;//订单pV
        $order_type=$params['order_type'];

        $items=[];
        foreach ($goods_list as $glv){
            $item=[];
            $product_id=$glv['product_id'];
            $quantity=$glv['quantity'];
            $options_index=$glv['options_index'];
            $optionsIndex = $this->parseOptions($options_index);
            $product=ProductModel::with(['image_preview'])->where('id',$product_id)->first();
            $price=$product->price;
            $description='';
            //有变体
            if($product->is_with_variants){
                foreach ($product->variants as $variant) {
                    $id = $variant['id'];
                    $optionVal = null;
                    if(array_key_exists($id, $optionsIndex) && !empty($optionsIndex[$id])){
                        $optionVal = $optionsIndex[$id];
                    }
                    if($optionVal == null && !$variant['optional']){
                        throw new ApplicationException('请选择'.$variant['variant']);
                    }
                    foreach ($variant['items'] as $viv){
                        if($optionVal==$viv['ref']){
                            if($description){
                                $description.=",".$variant['variant'].":".$viv['val'];
                            }else{
                                $description=$variant['variant'].":".$viv['val'];
                            }
                            if($viv['price']){
                                $price=bcadd($price,$viv['price'],2);
                            }
                        }
                    }
                }
            }
            //积分商城
            if($order_type=='score'){
                $score_goods=ScoreGoodsModel::where('product_id',$product->id)->where('status',1)->first();
                if(!$score_goods){
                    throw new ApplicationException('未获取积分商品信息');
                }
                $price=$score_goods->price;
                $score=$score_goods->score;
                $item_score_amount = floatval($score) * intval($quantity);
                $score_amount+=$item_score_amount;
                $item['score']=$item_score_amount;
            }
            //分销商城计算商品PV值
            $reg_goods=RegGoodsModel::where('product_id',$product->id)->where('status',1)->first();
            if($reg_goods){
                $goods_pv=$reg_goods->pv;
                $item_pv = floatval($goods_pv) * intval($quantity);
                $order_pv+=$item_pv;
                $item['pv']=$item_pv;
            }

            $item_total = floatval($price) * intval($quantity);
            $shipping_fee=$product->shipping_fee;
            $dispatch_amount+=$shipping_fee;
            $total+=$item_total;
            $item['product_id']=$product->id;
            $item['name']=$product->name;
            $item['index']=$options_index;
            $item['description']=$description;
            $item['title']=$product->name;
            $item['price']=$price;
            $item['quantity']=$quantity;
            $item['total']=$item_total;
            $item['thumb']=$product->image_preview->getDiskPath();
            $item['thumb_path']=url('/storage/app/'.$product->image_preview->getDiskPath());
            $items[]=$item;
        }
        $goods_amount= $total;
        $invoice_amount=$total;
        $total=$total+$dispatch_amount;
        $return['items']=$items;//订单条目
        $return['coupon_fee']=$coupon_fee;//优惠金额
        $return['discount_fee']=$discount_fee;//打折金额
        $return['goods_amount']=$goods_amount;//商品总额
        $return['invoice_amount']=$invoice_amount;//发票金额
        $return['dispatch_amount']=$dispatch_amount;//订单运费
        $return['dispatch_discount_money']=$dispatch_discount_money;//运费折扣金额
        $return['score_amount']=$score_amount;//积分总额
        $return['pv']=$order_pv;//积分总额
        $return['total']=$total;//合计
        $return['need_address']=1;//是否需要收货地址,后期增加虚拟商品是不用收货地址的，预留字段
        return $return;
    }

    /**
     * 解析选项
     * @param $option_index
     * @return array
     */
    protected function parseOptions($option_index){
        $option_index = explode(',', $option_index);
        $options = [];

        foreach ($option_index as $el) {
            if(empty($el))
                continue;

            $el = explode('::', $el);
            $options[$el[0]] = $el[1];
        }

        return $options;
    }
}
